package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author MiniApple
 * @date 2020/6/6 - 20:08
 */
@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    /**
     * 分页查询品牌
     * @param key
     * @param page
     * @param rows
     * @param sortBy
     * @param desc
     * @return
     */
    public PageResult<Brand> queryBrandByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        //初始化example对象，理论上通过example类可以构造你想到的任何筛选条件，工具类
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();//将来可以添加模糊查询
        //添加模糊查询
        if(StringUtils.isNotBlank(key)){
            criteria.andLike("name","%" + key + "%").orEqualTo("letter",key);
        }

        //添加分页
        //调用PageHelper获取第1页，5条内容，默认查询总数count
        PageHelper.startPage(page,rows);

        //添加排序
        if (StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy + (desc ? " desc":" asc"));
        }

        //找到适合的通用mapper方法
        List<Brand> brands = this.brandMapper.selectByExample(example);
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);

        return new PageResult<>(pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 新增品牌
     * @param brand
     * @param cids
     * 修改操作需要添加事务
     */
    @Transactional
    public void saveBrand(Brand brand, List<Long> cids) {
        //新增品牌,insertSelective效率更高
        this.brandMapper.insertSelective(brand);
        cids.forEach(cid -> this.brandMapper.saveCategoryAndBrand(cid,brand.getId()));
    }

    /**
     * 根据分类的id查询品牌的集合
     * @param cid
     * @return
     */
    public List<Brand> queryBrandsByCid(Long cid) {
        return this.brandMapper.selectByCid(cid);
    }

    /**
     * 根据id查询品牌
     * @param id
     * @return
     */
    public Brand queryBrandById(Long id) {
        return this.brandMapper.selectByPrimaryKey(id);
    }
}
